package com.syezon.wifikey.ad;

import android.Manifest;
import android.app.Activity;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;

import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener;
import com.qq.e.comm.util.AdError;

import com.syezon.wifikey.BuildConfig;
import com.syezon.wifikey.analysis.event.EventEnum;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.GDTConfig;
import com.syezon.wifikey.config.TTAdManagerHolder;
import com.syezon.wifikey.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class InterAd implements CommonAdCallBack {

    private static final String TAG_LOG = "inter_ad";

    private Activity activity;
    private List<String> mInterAdOrderList = new ArrayList<>();

    private TTNativeExpressAd ttNativeExpressAd;
    private UnifiedInterstitialAD interstitialAD;
    private OnShowSelfADListener onShowSelfADListener;
    private List<AdInfo> adInfos;
    private int retryCount;
    private OnSGShowListener onSGShowListener;

    public void setOnSGShowListener(OnSGShowListener onSGShowListener) {
        this.onSGShowListener = onSGShowListener;
    }

    public InterAd(Activity activity) {
        this.activity = activity;
    }

    public void setAdInfos(List<AdInfo> adInfos) {
        this.adInfos = adInfos;
    }

    public interface OnSGShowListener {
        //void onShowSGAd(List<SGSelfRenderingData> list, AdInfo adInfo);
    }

    public void setOnShowSelfADListener(OnShowSelfADListener onShowSelfADListener) {
        this.onShowSelfADListener = onShowSelfADListener;
    }

    public interface OnShowSelfADListener {
        void onShowSelfAd(AdInfo adInfo);
    }


    public void loadInterAd() {
        AdInfo adInfo = InterAdConfig.getPopAdSource();
        mInterAdOrderList = InterAdConfig.getPopAdOrderList();
        boolean permission = PermissionUtils.isGranted(Manifest.permission.READ_PHONE_STATE);
        loadNewInterAd(adInfo);
    }

    private void loadNewInterAd(AdInfo adInfo) {
        //加载广告
        if (activity == null || adInfo == null) {
            return;
        }

        //判断广告类型
        if (adInfo.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
            loadCSJTTInteractionAd(adInfo);
        } else if (adInfo.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG) {
            loadGdtByCode(adInfo);
        } else if (adInfo.getType() == AdInfo.AD_TYPE_SOUGOU) {
            //loadSGAd(adInfo);
        }
        if (adInfo.getType() == AdInfo.AD_TYPE_WEB || adInfo.getType() == AdInfo.AD_TYPE_DEEPLINK || adInfo.getType() == AdInfo.AD_TYPE_APK) {
            InterAdConfig.saveLastPopAd(adInfo);
            if (onShowSelfADListener != null) {
                onShowSelfADListener.onShowSelfAd(adInfo);
            }
        }
    }


    public void loadInterAd(String adSource) {
        if (InterAdConfig.INTER_AD_SOURCE_TT.equals(adSource)) {
            loadCSJTTInteractionAd();
        } else if (InterAdConfig.INTER_AD_SOURCE_GDT.equals(adSource)) {
            loadGdt();
        } else if (InterAdConfig.INTER_AD_SOURCE_SG.equals(adSource)) {
            //loadSGAd();
        }
    }

//    private void loadSGAd(final AdInfo adInfo) {
//        String code = adInfo.getCode();
//        String[] split = code.split(",");
//        String mid = "2651";
//        String pid = "hzxl2018_app_8";
//
//        if (split.length == 2) {
//            mid = split[1];
//            pid = split[0];
//        }
//        final AdClient adClient = AdClient.newClient(activity.getApplicationContext())
//                .pid(pid)
//                .mid(mid)// 必填：代码位ID
//                .addAdTemplate(AdTemplate.DOWNLOAD_BIG_TPL_ID)
//                .addAdTemplate(AdTemplate.BIG_IMG_TPL_ID)//设置模板，可以添加多个模板
//                .debug(true)//debug设置true打印相关日志，上线关闭
//                .create();
//        adClient.with(activity).fetchSGSelfRenderingAd(new SGAdNative.SGSelfRenderingADListener() {
//            @Override
//            public void onSGSelfRenderingLoad(List<SGSelfRenderingData> list) {
//                //这里加载成功不需要上报，SGSelfRenderingData有加载成功和失败的回调
//                updateSGAd(list,adInfo);
//                onLoadSuccess(adInfo);
//            }
//
//            @Override
//            public void onError(SGAdError sgAdError) {
//                ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
//                onLoadFail(adInfo, sgAdError.getErrorMessage());
//            }
//        });
//    }

//    private void updateSGAd(List<SGSelfRenderingData> list, AdInfo adInfo) {
//        if(list == null || list.isEmpty()){
//            return;
//        }
//        if(onSGShowListener != null){
//            onSGShowListener.onShowSGAd(list,adInfo);
//        }
//    }

//    private void loadSGAd() {
//        String[] split = SGConfig.INTER_POS_ID.split(",");
//        String mid = split[1];
//        String pid = split[0];
//        AdClient adClient = AdClient.newClient(activity.getApplicationContext())
//                .pid(pid)
//                .mid(mid)// 必填：代码位ID
//                .addAdTemplate(AdTemplate.INSERT_HOR_ID)
//                .addAdTemplate(AdTemplate.INSERT_IMG_CHARACTER_ID)//设置模板，可以添加多个模板
//                .debug(true)//debug设置true打印相关日志，上线关闭
//                .create();
//        adClient.with(activity).fetchSGInsertAd(new SGAdNative.SGInsertAdListener() {
//            boolean reportDownload;
//            boolean reportShow;
//
//            @Override
//            public void onSGInsertLoad(SGInsertAd sgInsertAd) {
//
//                //加载插屏广告数据成功的回调
//                LogUtils.e("onSGInsertLoad");
//                sgInsertAd.setSGInsertInteractionListener(new SGInsertAd.AdInteractionListener() {
//                    @Override
//                    public void onAdShow() {
//                        if (!reportShow) {
//                            reportShow = true;
//                            SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, SGConfig.INTER_POS_ID, SDKReportHelper.OP_TYPE_SHOW);
//                        }
//                    }
//
//                    @Override
//                    public void onAdClose() {
//                        LogUtils.e("onAdClose");
//                    }
//
//                    @Override
//                    public void onAdClick() {
//                        //广告点击的回调
//                        SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_SG, SGConfig.INTER_POS_ID, SDKReportHelper.OP_TYPE_CLICK);
//                    }
//
//                    @Override
//                    public void onAdClickDownLoad() {
//                        //下载类型广告，点击下载的回调
//                        LogUtils.d("onAdClickDownLoad");
//                        if (!reportDownload) {
//                            reportDownload = true;
//                            SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_SG, SGConfig.INTER_POS_ID, SDKReportHelper.OP_TYPE_DOWNLOAD);
//                        }
//                    }
//
//                    @Override
//                    public void onAdError(SGAdError sgAdError) {
//                        //错误回调
//                        LogUtils.e("errorCode:" + sgAdError.getErrorCode() + "errorMessage:" + sgAdError.getErrorMessage());
//                        //获取广告异常的回调
//                        onLoadFail(IntAdConfig.INTER_AD_SOURCE_SG, sgAdError.getErrorMessage());
//                        SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_SG, SGConfig.INTER_POS_ID, SDKReportHelper.OP_TYPE_FAIL);
//                    }
//                });
//                //展示插屏广告
//                sgInsertAd.showSGInsertView();
//            }
//
//            @Override
//            public void onError(SGAdError sgAdError) {
//                //获取广告异常的回调
//                LogUtils.e("errorCode:" + sgAdError.getErrorCode() + "errorMessage:" + sgAdError.getErrorMessage());
//            }
//        });
//    }

    public void destroy() {
        if (ttNativeExpressAd != null) {
            ttNativeExpressAd.destroy();
        }
        if (interstitialAD != null) {
            interstitialAD.destroy();
        }
    }

    private void loadCSJTTInteractionAd(final AdInfo adInfo) {
        try {
            if (ttNativeExpressAd != null) {
                ttNativeExpressAd.destroy();
            }
            /**
             * 加载插屏广告
             */
            ReportAgent.reportAdvExtShow(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            //step4:创建插屏广告请求参数AdSlot,具体参数含义参考文档
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(adInfo.getCode())
                    .setAdCount(1) //请求广告数量为1到3条
                    .setExpressViewAcceptedSize(300, 0)
                    .setImageAcceptedSize(600, 900) //根据广告平台选择的尺寸，传入同比例尺寸
                    .build();
            //step5:请求广告，调用插屏广告异步请求接口
            TTAdManagerHolder.get().createAdNative(Utils.getApp()).loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                @Override
                public void onError(int i, String s) {
                    onLoadFail(adInfo, s);
                    ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }

                @Override
                public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                    if (list != null && list.size() > 0) {
                        ttNativeExpressAd = list.get(0);
                        ttNativeExpressAd.render();
                        ttNativeExpressAd.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {

                            boolean reportShow;

                            @Override
                            public void onAdDismiss() {

                            }

                            @Override
                            public void onAdClicked(View view, int i) {
                                ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                            }

                            @Override
                            public void onAdShow(View view, int i) {
                                if (!reportShow) {
                                    reportShow = true;

                                }
                            }

                            @Override
                            public void onRenderFail(View view, String s, int i) {

                            }

                            @Override
                            public void onRenderSuccess(View view, float v, float v1) {
                                if (ttNativeExpressAd != null && activity != null
                                        && !activity.isFinishing()) {
                                    ttNativeExpressAd.showInteractionExpressAd(activity);
                                }
                                onLoadSuccess(adInfo);
                            }
                        });
                        ttNativeExpressAd.setDownloadListener(new TTAppDownloadListener() {

                            boolean reportDownload;
                            boolean reportInstall;

                            @Override
                            public void onIdle() {

                            }

                            @Override
                            public void onDownloadActive(long l, long l1, String s, String s1) {

                            }

                            @Override
                            public void onDownloadPaused(long l, long l1, String s, String s1) {

                            }

                            @Override
                            public void onDownloadFailed(long l, long l1, String s, String s1) {

                            }

                            @Override
                            public void onDownloadFinished(long l, String s, String s1) {
                                if (!reportDownload) {
                                    reportDownload = true;
                                    ReportAgent.reportAdvDownload(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                                }
                            }

                            @Override
                            public void onInstalled(String s, String s1) {
                                if (!reportInstall) {
                                    reportInstall = true;
                                    ReportAgent.reportAdvInstall(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                                }
                            }
                        });
                    }
                }
            });
        } catch (Exception e) {

        }
    }

    private void loadCSJTTInteractionAd() {
        try {
            if (ttNativeExpressAd != null) {
                ttNativeExpressAd.destroy();
            }
            /**
             * 加载插屏广告
             */
            //step4:创建插屏广告请求参数AdSlot,具体参数含义参考文档
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(TTAdManagerHolder.INTERACTIONAD)
                    .setAdCount(1) //请求广告数量为1到3条
                    .setExpressViewAcceptedSize(300, 0)
                    .setImageAcceptedSize(600, 900) //根据广告平台选择的尺寸，传入同比例尺寸
                    .build();
            //step5:请求广告，调用插屏广告异步请求接口
            TTAdManagerHolder.get().createAdNative(Utils.getApp()).loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                @Override
                public void onError(int i, String s) {
                    onLoadFail(IntAdConfig.INTER_AD_SOURCE_TT, s);
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, TTAdManagerHolder.INTERACTIONAD, SDKReportHelper.OP_TYPE_FAIL);
                }

                @Override
                public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                    if (list != null && list.size() > 0) {
                        ttNativeExpressAd = list.get(0);
                        ttNativeExpressAd.render();
                        ttNativeExpressAd.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {

                            boolean reportShow;

                            @Override
                            public void onAdDismiss() {

                            }

                            @Override
                            public void onAdClicked(View view, int i) {
                                SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, TTAdManagerHolder.INTERACTIONAD, SDKReportHelper.OP_TYPE_CLICK);
                            }

                            @Override
                            public void onAdShow(View view, int i) {
                                if (!reportShow) {
                                    reportShow = true;
                                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, TTAdManagerHolder.INTERACTIONAD, SDKReportHelper.OP_TYPE_SHOW);
                                }
                            }

                            @Override
                            public void onRenderFail(View view, String s, int i) {

                            }

                            @Override
                            public void onRenderSuccess(View view, float v, float v1) {
                                if (ttNativeExpressAd != null && activity != null
                                        && !activity.isFinishing()) {
                                    ttNativeExpressAd.showInteractionExpressAd(activity);
                                }
                                onLoadSuccess(IntAdConfig.INTER_AD_SOURCE_TT);
                            }
                        });
                        ttNativeExpressAd.setDownloadListener(new TTAppDownloadListener() {

                            boolean reportDownload;
                            boolean reportInstall;

                            @Override
                            public void onIdle() {

                            }

                            @Override
                            public void onDownloadActive(long l, long l1, String s, String s1) {

                            }

                            @Override
                            public void onDownloadPaused(long l, long l1, String s, String s1) {

                            }

                            @Override
                            public void onDownloadFailed(long l, long l1, String s, String s1) {

                            }

                            @Override
                            public void onDownloadFinished(long l, String s, String s1) {
                                if (!reportDownload) {
                                    reportDownload = true;
                                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, TTAdManagerHolder.INTERACTIONAD, SDKReportHelper.OP_TYPE_DOWNLOAD);
                                }
                            }

                            @Override
                            public void onInstalled(String s, String s1) {
                                if (!reportInstall) {
                                    reportInstall = true;
                                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, TTAdManagerHolder.INTERACTIONAD, SDKReportHelper.OP_TYPE_INSTALL);
                                }
                            }
                        });
                    }
                }
            });
        } catch (Exception e) {

        }

    }

    private void onLoadSuccess(AdInfo adSourceCode) {
        InterAdConfig.saveLastPopAd(adSourceCode);
    }

    private void onLoadFail(AdInfo adSourceCode, String errorMsg) {
        LogUtils.e("onLoadFail  " + errorMsg);
        if (BuildConfig.DEBUG) {
            ToastUtils.showShort("插屏加载失败:       广告type:" + adSourceCode.getType() + "     errorMsg:" + errorMsg);
        }
        InterAdConfig.saveLastPopAd(adSourceCode);
        AdInfo adSource = InterAdConfig.getPopAdSource();
        //当只有一条sdk广告，并且加载失败的情况，开始走填充逻辑
        if (adInfos.size() == 1) {
            String oldAdSource = InterAdConfig.getOldAdSource();
            loadInterAd(oldAdSource);
            return;
        }
        retryCount++;
        if (adInfos.indexOf(adSource) == adInfos.size() - 1) {
            String oldAdSource = InterAdConfig.getOldAdSource();
            loadInterAd(oldAdSource);
            return;
        }
        loadNewInterAd(adSource);
    }


    private void loadGdtByCode(final AdInfo adInfo) {
        try {
            if (activity == null || activity.isFinishing()) {
                return;
            }
            if (interstitialAD != null) {
                interstitialAD.destroy();
            }
            interstitialAD = new UnifiedInterstitialAD(activity, GDTConfig.APP_ID, adInfo.getCode(), new UnifiedInterstitialADListener() {

                boolean reportShow;

                @Override
                public void onADReceive() {
                    try {
                        onLoadSuccess(adInfo);
                        interstitialAD.show();
                        if (!reportShow) {
                            reportShow = true;
                            ReportAgent.reportAdvExtShow(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                        }
                    } catch (Exception e) {

                    }

                }

                @Override
                public void onVideoCached() {

                }

                @Override
                public void onNoAD(AdError adError) {
                    String errorMsg = adError.getErrorMsg();
                    onLoadFail(adInfo, errorMsg);
                    ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }

                @Override
                public void onADOpened() {

                }

                @Override
                public void onADExposure() {

                }

                @Override
                public void onADClicked() {
                    ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }

                @Override
                public void onADLeftApplication() {

                }

                @Override
                public void onADClosed() {

                }
            });
            interstitialAD.loadAD();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadSuccess(String adSourceCode) {
        LogUtils.eTag(TAG_LOG, "onLoadSuccess " + adSourceCode);
        IntAdConfig.saveLastInterAdCode(adSourceCode);
    }

    @Override
    public void onLoadFail(String adSourceCode, String errorMsg) {
        LogUtils.eTag(TAG_LOG, "onLoadFail " + adSourceCode + " errorMsg " + errorMsg);
        //MobclickAgent.onEvent(com.blankj.utilcode.util.Utils.getApp(), EventEnum.POP_AD_EMPTY.eventId);
        String nextInterAdCode = InterAdConfig.getNextPopAdCode(adSourceCode, mInterAdOrderList, ++retryCount);
        loadInterAd(nextInterAdCode);
    }

    private void loadGdt() {
        try {
            if (activity == null || activity.isFinishing()) {
                return;
            }
            if (interstitialAD != null) {
                interstitialAD.destroy();
            }
            interstitialAD = new UnifiedInterstitialAD(activity, GDTConfig.APP_ID, GDTConfig.INTERSTITIAL_NEW_AD, new UnifiedInterstitialADListener() {

                boolean reportShow;

                @Override
                public void onADReceive() {
                    try {
                        onLoadSuccess(InterAdConfig.INTER_AD_SOURCE_GDT);
                        interstitialAD.show();
                        if (!reportShow) {
                            reportShow = true;
                            SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, GDTConfig.INTERSTITIAL_NEW_AD, SDKReportHelper.OP_TYPE_SHOW);
                        }
                    } catch (Exception e) {

                    }

                }

                @Override
                public void onVideoCached() {

                }

                @Override
                public void onNoAD(AdError adError) {
                    String errorMsg = adError.getErrorMsg();
                    onLoadFail(InterAdConfig.INTER_AD_SOURCE_GDT, errorMsg);
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, GDTConfig.INTERSTITIAL_NEW_AD, SDKReportHelper.OP_TYPE_FAIL);
                }

                @Override
                public void onADOpened() {

                }

                @Override
                public void onADExposure() {

                }

                @Override
                public void onADClicked() {
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, GDTConfig.INTERSTITIAL_NEW_AD, SDKReportHelper.OP_TYPE_CLICK);
                }

                @Override
                public void onADLeftApplication() {

                }

                @Override
                public void onADClosed() {

                }
            });
            interstitialAD.loadAD();
        } catch (Exception e) {

        }
    }


}
